<?php

namespace App\Services;

use App\Models\Order;
use App\Models\Dish;
use App\Repositories\OrderRepository;
use App\Repositories\RoomRepository;
use App\Exceptions\BusinessException;
use App\Helpers\DateTimeHelper;
use Illuminate\Support\Facades\DB;

class OrderService
{
    protected $orderRepository;
    protected $roomRepository;

    public function __construct(OrderRepository $orderRepository, RoomRepository $roomRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->roomRepository = $roomRepository;
    }

    /**
     * 提交订单
     */
    public function createOrder(array $data, int $userId): Order
    {
        DB::beginTransaction();
        
        try {
            $room = $this->roomRepository->findByRoomId($data['roomId']);
            
            if (!$room) {
                throw new BusinessException('房间不存在', 10001);
            }

            if ($room->status !== 'active') {
                throw new BusinessException('房间已关闭', 10002);
            }

            // 检查用户是否在房间中
            if (!$this->isUserInRoom($room->id, $userId)) {
                throw new BusinessException('您不在此房间中', 10004);
            }

            // 检查是否已有待处理订单
            $existingOrder = $this->orderRepository->getByRoomAndUser($room->id, $userId);
            if ($existingOrder && $existingOrder->status === 'pending') {
                throw new BusinessException('您已在此房间中提交过订单', 20001);
            }

            // 验证菜品
            $dishes = $this->validateDishes($data['dishes']);
            
            // 创建订单
            $orderData = [
                'order_id' => Order::generateOrderId(),
                'room_id' => $room->id,
                'user_id' => $userId,
                'dishes' => $dishes,
                'status' => 'pending',
                'payment_status' => 'unpaid',
            ];

            $order = $this->orderRepository->create($orderData);

            // 更新房间统计
            $this->updateRoomStats($room);

            DB::commit();
            return $order;

        } catch (BusinessException $e) {
            DB::rollBack();
            throw $e;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BusinessException('提交订单失败：' . $e->getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetail(string $orderId, int $userId): array
    {
        $order = $this->orderRepository->findByOrderId($orderId);
        
        if (!$order) {
            throw new BusinessException('订单不存在', 20002);
        }

        // 检查权限（订单创建者或房间成员可以查看）
        $room = $this->roomRepository->find($order->room_id);
        if ($order->user_id !== $userId && !$this->isUserInRoom($room->id, $userId)) {
            throw new BusinessException('无权限查看此订单', 20003);
        }

        // 获取房间信息
        $room = $this->roomRepository->find($order->room_id);
        
        // 获取房间所有订单，用于计算参与者信息
        $roomOrders = $this->orderRepository->getByRoom($room->id);
        
        // 构建参与者信息
        $participants = $this->buildParticipantsInfo($roomOrders);
        
        // 计算统计信息
        $totalParticipants = count($participants);
        $totalItems = $roomOrders->sum(function ($order) {
            return collect($order->dishes)->sum('quantity');
        });

        // 构建订单详情
        return [
            'order_id' => $order->order_id,
            'order_number' => $this->generateOrderNumber($order),
            'room_id' => $room->room_id,
            'status' => $order->status,
            'created_at' => $order->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $order->updated_at->format('Y-m-d H:i:s'),
            'room' => [
                'room_id' => $room->room_id,
                'title' => $room->title,
                'type' => $room->type,
            ],
            'dishes' => $this->formatOrderDishes($order->dishes),
            'participants' => $participants,
            'total_participants' => $totalParticipants,
            'total_items' => $totalItems,
            'rating' => null, // 暂时为null，后续可扩展
        ];
    }

    /**
     * 获取用户订单
     */
    public function getUserOrders(int $userId): \Illuminate\Database\Eloquent\Collection
    {
        return $this->orderRepository->getByUser($userId);
    }

    /**
     * 获取房间订单
     */
    public function getRoomOrders(string $roomId, int $userId): \Illuminate\Database\Eloquent\Collection
    {
        $room = $this->roomRepository->findByRoomId($roomId);
        
        if (!$room) {
            throw new BusinessException('房间不存在', 10001);
        }

        if (!$this->isUserInRoom($room->id, $userId)) {
            throw new BusinessException('无权限访问房间订单', 10004);
        }

        return $this->orderRepository->getByRoom($room->id);
    }

    /**
     * 取消订单
     */
    public function cancelOrder(string $orderId, int $userId): void
    {
        $order = $this->orderRepository->findByOrderId($orderId);
        
        if (!$order) {
            throw new BusinessException('订单不存在', 20002);
        }

        if ($order->user_id !== $userId) {
            throw new BusinessException('无权限取消此订单', 20003);
        }

        if ($order->status !== 'pending') {
            throw new BusinessException('订单状态不允许取消', 20004);
        }

        $this->orderRepository->cancel($order->id);
    }

    /**
     * 确认订单
     */
    public function confirmOrder(string $orderId, int $userId): void
    {
        $order = $this->orderRepository->findByOrderId($orderId);
        
        if (!$order) {
            throw new BusinessException('订单不存在', 20002);
        }

        // 检查权限（只有房间创建者可以确认订单）
        $room = $this->roomRepository->find($order->room_id);
        if ($room->creator_id !== $userId) {
            throw new BusinessException('无权限确认此订单', 20003);
        }

        if ($order->status !== 'pending') {
            throw new BusinessException('订单状态不允许确认', 20004);
        }

        $this->orderRepository->confirm($order->id);
    }

    /**
     * 验证菜品
     */
    private function validateDishes(array $dishes): array
    {
        $validatedDishes = [];
        
        foreach ($dishes as $dish) {
            $dishModel = Dish::find($dish['dishId']);
            
            if (!$dishModel) {
                throw new BusinessException("菜品不存在：{$dish['dishId']}", 20005);
            }

            if (!$dishModel->is_available) {
                throw new BusinessException("菜品不可用：{$dishModel->name}", 20006);
            }

            $validatedDishes[] = [
                'dish_id' => $dishModel->id,
                'name' => $dishModel->name,
                'quantity' => $dish['quantity'],
                'flavor' => $dish['flavor'] ?? null,
                'note' => $dish['note'] ?? null,
            ];
        }

        return $validatedDishes;
    }


    /**
     * 检查用户是否在房间中
     */
    private function isUserInRoom(int $roomId, int $userId): bool
    {
        return \App\Models\RoomMember::where('room_id', $roomId)
            ->where('user_id', $userId)
            ->exists();
    }

    /**
     * 更新房间统计
     */
    private function updateRoomStats($room): void
    {
        $stats = $this->orderRepository->getRoomStats($room->id);
        
        $this->roomRepository->updateStats($room->id, [
            'total_orders' => $stats['total_orders'],
        ]);
    }

    /**
     * 获取订单统计
     */
    public function getOrderStats(int $roomId): array
    {
        return $this->orderRepository->getRoomStats($roomId);
    }

    /**
     * 构建参与者信息
     */
    private function buildParticipantsInfo($roomOrders): array
    {
        $participants = [];
        
        foreach ($roomOrders as $order) {
            $user = $order->user;
            $participantKey = $user->id;
            
            if (!isset($participants[$participantKey])) {
                $participants[$participantKey] = [
                    'user_id' => $user->id,
                    'nickname' => $user->nickname ?? '用户' . $user->id,
                    'dishes' => [],
                    'item_count' => 0,
                ];
            }
            
            // 添加该用户的菜品
            foreach ($order->dishes as $dish) {
                $participants[$participantKey]['dishes'][] = [
                    'dish_id' => $dish['dish_id'],
                    'name' => $dish['name'],
                    'quantity' => $dish['quantity'],
                    'flavor' => $dish['flavor'] ?? '',
                    'note' => $dish['note'] ?? '',
                ];
                $participants[$participantKey]['item_count'] += $dish['quantity'];
            }
        }
        
        return array_values($participants);
    }

    /**
     * 格式化订单菜品信息
     */
    private function formatOrderDishes(array $dishes): array
    {
        return array_map(function ($dish) {
            $options = [];
            if (!empty($dish['flavor'])) {
                $options[] = $dish['flavor'];
            }
            if (!empty($dish['note'])) {
                $options[] = $dish['note'];
            }
            
            return [
                'dish_id' => $dish['dish_id'],
                'name' => $dish['name'],
                'quantity' => $dish['quantity'],
                'flavor' => $dish['flavor'] ?? '',
                'note' => $dish['note'] ?? '',
                'options' => $options,
            ];
        }, $dishes);
    }

    /**
     * 生成订单号
     */
    private function generateOrderNumber($order): string
    {
        // 使用订单创建时间生成订单号
        $date = $order->created_at->format('Ymd');
        $time = $order->created_at->format('His');
        return $date . $time;
    }

}
